package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class Server {
	private Socket client;
	private ServerSocket server;
	private OutputStream output;
	private InputStream input;
	boolean verbindung1;
	boolean gesendet;
	
	Thread verbindung;
	Thread senden;
	Thread empfangen;
	
	public Server() throws IOException{
		server = new ServerSocket(1234);
		verbindung1 = false;
		gesendet = false;
	
	}
	public void verbinde(){
		Thread verbindung = new Thread(new Verbindung());
		verbindung.start();
	}
	
	public static void main(String[] args){
		try {
			Server server = new Server();
			server.verbinde();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	private class Verbindung implements Runnable{

		public void run(){
			System.out.println("Hello");
			try{
				while (true){
					client = server.accept();
					System.out.println("Thread");
					verbindung1 = true;
					Thread senden = new Thread(new Senden());
					senden.start();
					}
				}
				catch (IOException e){
				}
			}
		}
	private class Senden implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				output = client.getOutputStream();
				System.out.println(gesendet);
				output.write(2);
				output.flush();
				
				Thread empfangen = new Thread(new Empfangen());
				empfangen.start();
				gesendet = true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	private class Empfangen implements Runnable{

		@Override
		public void run() {
			try {
				input = client.getInputStream();
				System.out.println(input.read());
				System.out.println("Server empfängt!!!");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		
	}

}
